package com.imagecollector.common.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.imagecollector.common.constant.RedisConstant;
import com.imagecollector.common.utils.RedisUtils;
import com.imagecollector.domain.entity.District;
import com.imagecollector.domain.vo.DistrictVO;
import com.imagecollector.service.IDistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Author: wrf
 * @Date: 2024/7/5 15:02
 * @Description: 容器启动时的监听类
 */
@Component
@Slf4j
public class ApplicationStartupEventHandler {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IDistrictService districtService;

    private static final List<String> DELETE_PREFIX_LIST = ListUtil.toList(
            RedisConstant.DISTRICT);

    @EventListener(ApplicationReadyEvent.class)
    public void handleApplicationReady() {
        redisUtils.cleanCacheByPrefix(DELETE_PREFIX_LIST);
        setDistrictCache();
    }

    private void setDistrictCache() {
        Map<Integer, DistrictVO> allChildrenList = districtService.allChildrenList();
        if (CollectionUtil.isNotEmpty(allChildrenList)) {
            allChildrenList.forEach((districtId, childrenList) -> redisUtils.set(RedisConstant.DISTRICT + districtId, childrenList));
            log.info("地区信息添加缓存完毕...");
        }
    }

}
